﻿using Abp.IdentityFramework;
using Abp.UI;
using Abp.Web.Mvc.Controllers;
using Microsoft.AspNet.Identity;
using System;
using System.IO;
using System.Web;

namespace NavGuide.Web.Controllers
{
    /// <summary>
    /// Derive all Controllers from this class.
    /// </summary>
    public abstract class NavGuideControllerBase : AbpController
    {
        protected NavGuideControllerBase()
        {
            LocalizationSourceName = NavGuideConsts.LocalizationSourceName;
        }

        protected virtual void CheckModelState()
        {
            if (!ModelState.IsValid)
            {
                throw new UserFriendlyException(L("FormIsNotValidMessage"));
            }
        }

        protected void CheckErrors(IdentityResult identityResult)
        {
            identityResult.CheckErrors(LocalizationManager);
        }

        #region 辅助方法 

        protected dynamic UploadFile(HttpPostedFileBase postedfile, string uploadpath, bool hasDateFolder = true, string fileName = "")
        {
            if (hasDateFolder) uploadpath += DateTime.Now.ToString("yyyyMMdd") + "/";
            string directory = System.Web.HttpContext.Current.Server.MapPath(uploadpath);
            if (!Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
            }
            string postedFileName = Path.GetFileName(postedfile.FileName);
            string newFileName = "";
            //  string finalPath = "";
            string savePath = "";
            string extention = postedFileName.Substring(postedFileName.IndexOf("."));
            newFileName = Guid.NewGuid().ToString("N") + extention;
            savePath = Path.Combine(directory, newFileName);
            // finalPath = uploadpath.TrimStart('~') + newFileName;

            //文件存在就删除文件
            if (System.IO.File.Exists(savePath))
            {
                System.IO.File.Delete(savePath);
            }
            postedfile.SaveAs(savePath);

            if (string.IsNullOrWhiteSpace(fileName)) { fileName = postedFileName; }

            return new
            {
                FileName = fileName
                // , FilePath = finalPath
                ,
                SavePath = savePath
            };
        }
        
        // 通过字符串，分隔符返回string[]数组 
        public string[] StringSplit(string s, char[] separtor)
        {
            string[] tempFileds = s.Trim().Split(separtor); return tempFileds;
        }

        #endregion
    }
}